import React from 'react';
import { Tree, Input } from 'antd';
import styles from './index.less';
import { list } from '@/services/Organization';

class Left extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      treeData: [],
      selectedKeys: []
    }
  }

  /* 
  * 获取树数据列表
  */
  async getTrees() {
    try {
      const { select } = this.props;
      const res = await list();
      const threes = this._getThrees([res]);
      this.setState({ 
        treeData: threes,
        selectedKeys: [threes[0].key] 
      });
      select ? select(threes[0].key) : null;
    } catch (e) {
      console.log('Organization:', e)
    }
  }

  /* 获取树数据 */
  _getThrees = (list) => {
    const arr = [];
    if (!list || list.length === 0) return [];
    for (let i = 0; i < list.length; i++) {
      const item = list[i];
      arr.push({
        key: item.id,
        title: item.name,
        children: this._getThrees(item.childUnit)
      })
    }
    return arr
  }

  /* 监听选择项 */
  onSelect = (item) => {
    const { select } = this.props;
    const unitId = item[0];
    select ? select(unitId) : null;
  }

  componentDidMount() {
    this.getTrees();
  }

  render() {
    const { onSelect } = this;
    const { treeData, selectedKeys } = this.state;
    if (!treeData || treeData.length === 0) return null;
    return (
      <div className={styles.leftContainer}>
        {/* <Input.Search className={styles.search} placeholder="Search" /> */}
        <Tree
          blockNode
          defaultExpandAll
          defaultSelectedKeys={selectedKeys}
          treeData={treeData}
          onSelect={onSelect} />
      </div>
    )
  }
}

export default Left;
